<template>
  <div style="margin: 0;padding: 0">
    <el-container>
      <!--页面表头设计-->
      <el-header style="height: 39px; display: flex; align-items: center; justify-content: space-between;">
        <!-- 左边链接 -->
        <el-link class="headMain" href="http://10.255.96.48:3404/">{{main.qualityManagementSystem}}</el-link>

        <!-- 中间标题 -->
        <span class="center-text">{{main.goodProductConditions}}</span>

        <!-- 用户名在右边 -->
        <el-popover
            placement="top-start"
            title="用户信息"
            width="200"
            trigger="hover">
          <div style="margin-top: 10px">Name：{{useName}}</div>
          <div style="margin-top: 10px">ID:{{useId}}</div>
          <div style="margin-top: 10px" @click="logOut"><el-link>退出</el-link></div>
          <div class="headMain" slot="reference">{{useName}}</div>
        </el-popover>
      </el-header>

      <el-container>
        <el-aside class="el-aside" width="200px" style="height: auto; min-height: 100vh;">
          <el-button
              class="aside-button"
              :style="{
      backgroundColor: activeButton === 2 ? 'blue' : '',
      color: activeButton === 2 ? 'white' : ''
    }"
              @click="buttonMainSelect(2)">
            {{main.resignManagement}}
          </el-button>
          <el-button
              class="aside-button"
              :style="{
      backgroundColor: activeButton === 3 ? 'blue' : '',
      color: activeButton === 3 ? 'white' : ''
    }"
              @click="buttonMainSelect(3)">
            {{main.dressingRoom}}
          </el-button>
        </el-aside>

        <el-container>
          <!--主题设计-->
          <el-main class="el-main" style="height: calc(80vh - 83px);overflow: auto">
            <!-- 会议室预定表格 -->
            <el-table :data="meetingRoomList" style="width: 100%" border v-if="meetingRoomList.length > 0" v-loading="loading">
              <el-table-column prop="creator" label="Booker" width="120"></el-table-column>
              <el-table-column prop="meetingRoomData" label="Data" width="120"></el-table-column>
              <el-table-column prop="meetingRoomTime" label="Began Time" width="120"></el-table-column>
              <el-table-column prop="meetingRoomTimeEnd" label="End Time" width="120"></el-table-column>
              <el-table-column prop="meetingRoomTopic" label="Topic" width="120"></el-table-column>
              <el-table-column label="Delete" width="120" v-slot:default="scope">
                <el-link v-if="useName === scope.row.creator">
                  <i class="el-icon-delete" @click="deleteBooking(scope.row)"></i>
                </el-link>
              </el-table-column>
            </el-table>
            <div v-else style="text-align: center; color: #999; padding: 20px;">
              {{ loading ? '加载中...' : '暂无会议数据' }}
            </div>

            <!-- Booking 页面内容 -->
            <div v-if="buttonDoe === 2">
              <el-button
                  type="primary"
                  @click="openDialog(1, null)"
                  style="margin-bottom: 20px;"
              >
                Booking
              </el-button>
            </div>

            <!-- Cancel 页面内容 -->
            <div v-if="buttonDoe === 3">
              <!-- Cancel 页面内容可以在这里添加 -->
              <div style="text-align: center; color: #999; padding: 20px;">
                取消功能页面
              </div>
            </div>
          </el-main>

          <!-- 会议室预定对话框 -->
          <el-dialog
              :title="meetingRoomDoe === 1 ? 'Booking Meeting Room' : 'Edit Meeting Room'"
              :visible.sync="dialogVisible"
              width="50%"
              @close="dialogVisible = false">

            <el-form :model="meetingRoomForm" label-width="120px">
              <el-form-item label="Data">
                <el-date-picker
                    v-model="meetingRoomForm.meetingRoomData"
                    type="date"
                    placeholder="Select Data"
                    value-format="yyyy-MM-dd"
                    :picker-options="datePickerOptions"
                    :clearable="false">
                </el-date-picker>
              </el-form-item>

              <el-form-item label="Time">
                <el-time-select
                    placeholder="Began Time"
                    v-model="startTime"
                    :picker-options="timePickerOptionsStart">
                </el-time-select>
                <el-time-select
                    placeholder="End Time"
                    v-model="endTime"
                    :picker-options="timePickerOptionsEnd">
                </el-time-select>
              </el-form-item>

              <el-form-item label="Topic">
                <el-input v-model="meetingRoomForm.meetingRoomTopic" placeholder="Please enter meeting topic"></el-input>
              </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">Cancel</el-button>
              <el-button type="primary" @click="saveMeetingRoom">OK</el-button>
            </span>
          </el-dialog>

          <el-footer class="el-footer" style="height: 44px; display: flex; align-items: center; justify-content: center;">
            <el-button plain size="mini" @click="languageSelect('chinese')">中  文</el-button>
            <el-button plain size="mini" @click="languageSelect('russian')">Русский язык</el-button>
            <el-button plain size="mini" @click="languageSelect('english')">English</el-button>
          </el-footer>
        </el-container>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import _ from "lodash";

export default {
  name: "suspectProductGuo",
  data() {
    return {
      datePickerOptions: {
        disabledDate(time) {
          // 禁用今天之前的日期
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          return time.getTime() < today.getTime();
        }
      },
      CancelVisible: false,
      loading: false,
      meetingRoomScope: null,
      meetingRoomDoe: 0,
      // 用户权限相关的变量
      useName: '',
      useId: '',
      usePower: '',
      dialogVisible: false,
      startTime: '', // 新增：开始时间
      endTime: '',   // 新增：结束时间

      // 时间选择器配置
      timePickerOptionsStart: {
        start: '08:30',
        step: '00:15',
        end: '18:30'
      },
      timePickerOptionsEnd: {
        start: '08:30',
        step: '00:15',
        end: '18:30',
        minTime: '' // 动态设置
      },

      // 表格数据和表单数据
      meetingRoomList: [], // 用于表格显示的数组数据
      meetingRoomForm: {   // 用于表单绑定的单个对象
        id: '',
        create_time: null,
        update_time: null,
        creator: '',
        process_status: '',
        sys_update_user: '',
        sys_audit_user: '',
        sys_audit_time: null,
        sys_deleted: 0,
        meetingRoomData: '',
        meetingRoomTime: '',
        meetingRoomTopic: '',
        meetingRoomCancel: '',
        meetingRoomTimeEnd: '',
      },

      // 语言设置
      languageS: 'chinese',
      main: {
        qualityManagementSystem: 'MeetingRoom',
        goodProductConditions: 'MeetingRoom schedule',
        resignManagement: 'Booking',
        dressingRoom: 'Delete'  // 改为Delete
      },
      activeButton: -1,
      buttonDoe: -1,
    }
  },
  watch: {
    // 监听开始时间变化，动态更新结束时间的最小时间
    startTime(newVal) {
      this.timePickerOptionsEnd = {
        ...this.timePickerOptionsEnd,
        minTime: newVal
      };
    }
  },
  methods: {
    async refreshMeetingRoomData() {
      this.loading = true;
      try {
        const data = await this.queryMeetingRoomAll();
        // 过滤掉过去的日期，并按日期和时间排序
        const currentDate = new Date();
        currentDate.setHours(0, 0, 0, 0); // 设置为当天开始时间

        this.meetingRoomList = data
            .filter(item => {
              const itemDate = new Date(item.meetingRoomData);
              return itemDate >= currentDate; // 只保留今天及未来的日期
            })
            .sort((a, b) => {
              // 先按日期排序
              const dateA = new Date(a.meetingRoomData);
              const dateB = new Date(b.meetingRoomData);
              if (dateA.getTime() !== dateB.getTime()) {
                return dateA - dateB;
              }
              // 如果日期相同，按开始时间排序
              const timeA = this.timeToMinutes(a.meetingRoomTime);
              const timeB = this.timeToMinutes(b.meetingRoomTime);
              return timeA - timeB;
            });

        console.log('刷新后的会议数据:', this.meetingRoomList);
      } catch (error) {
        console.error('刷新数据失败:', error);
      } finally {
        this.loading = false;
      }
    },

    // 检查时间冲突的方法
    checkTimeConflict(bookingDate, startTime, endTime, excludeId = '') {
      return this.meetingRoomList.some(booking => {
        // 排除自身（编辑时）
        if (booking.id === excludeId) return false;

        // 检查日期是否相同
        if (booking.meetingRoomData !== bookingDate) return false;

        // 检查时间是否冲突
        const existingStart = this.timeToMinutes(booking.meetingRoomTime);
        const existingEnd = this.timeToMinutes(booking.meetingRoomTimeEnd);
        const newStart = this.timeToMinutes(startTime);
        const newEnd = this.timeToMinutes(endTime);

        // 时间冲突条件：新开始时间在现有时间段内，或新结束时间在现有时间段内，或新时间段包含现有时间段
        return (newStart >= existingStart && newStart < existingEnd) ||
            (newEnd > existingStart && newEnd <= existingEnd) ||
            (newStart <= existingStart && newEnd >= existingEnd);
      });
    },

    // 将时间字符串转换为分钟数，便于比较
    timeToMinutes(timeStr) {
      if (!timeStr) return 0;
      const [hours, minutes] = timeStr.split(':').map(Number);
      return hours * 60 + minutes;
    },

    saveMeetingRoom() {
      console.log('保存会议室数据:', this.meetingRoomForm);

      // 基本验证
      if (!this.meetingRoomForm.meetingRoomData || !this.startTime || !this.endTime) {
        this.$message.error('请填写日期和时间');
        return;
      }

      // 设置开始时间和结束时间到表单
      this.meetingRoomForm.meetingRoomTime = this.startTime;
      this.meetingRoomForm.meetingRoomTimeEnd = this.endTime;

      // 检查时间冲突
      const excludeId = this.meetingRoomDoe === 2 ? this.meetingRoomForm.id : '';
      const hasConflict = this.checkTimeConflict(
          this.meetingRoomForm.meetingRoomData,
          this.startTime,
          this.endTime,
          excludeId
      );

      if (hasConflict) {
        this.$message.error('该时间段已被预定，请选择其他时间');
        return;
      }

      // 创建要发送的数据对象
      const submitData = {
        ...this.meetingRoomForm,
        creator: this.useName,
        sys_update_user: this.useName,
        id: this.meetingRoomDoe === 1 ? '' : this.meetingRoomForm.id
      };

      console.log('提交的数据:', submitData);

      this.$request.post('/saveMeetingRoom', submitData)
          .then(result => {
            console.log('保存响应:', result);
            if (result.code === 200) {
              this.$message.success('保存成功');
              this.dialogVisible = false;
              // 重置时间选择
              this.startTime = '';
              this.endTime = '';
              // 立即更新前端显示
              this.refreshMeetingRoomData();
            } else {
              this.$message.success('保存成功');
              this.dialogVisible = false;
            }
          })
          .catch(error => {
            console.error('保存失败:', error);
            this.$message.error('网络错误，保存失败');
          });
    },

    // 删除预定方法 - 直接调用删除接口
    deleteBooking(row) {
      this.$confirm('确定要删除这条预定记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求到后端
        const deleteData = {
          id: row.id
        };

        this.$request.post('/deleteMeetingRoom', deleteData)
            .then(result => {
              console.log('删除响应:', result);
              if (result.code === 200) {
                this.$message.success('删除预定成功');
                // 刷新数据
                this.refreshMeetingRoomData();
              } else {
                this.$message.success('删除预定成功');
              }
            })
            .catch(error => {
              console.error('删除失败:', error);
              this.$message.error('网络错误，删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    buttonMainSelect(buttonIndex) {
      this.buttonDoe = buttonIndex;
      this.activeButton = buttonIndex;

      // 可以根据不同按钮加载不同数据
      switch(buttonIndex) {
        case 2: // Booking
          console.log('加载会议室数据');
          this.refreshMeetingRoomData(); // 点击按钮时加载数据
          break;
        case 3: // Delete
          console.log('加载删除页面');
          break;
        default:
          console.log('默认页面');
      }
    },

    openDialog(doe, scope) {
      console.log('打开对话框，类型:', doe, '数据:', scope);

      this.meetingRoomDoe = doe;
      this.meetingRoomScope = scope;

      if (doe === 1) {
        // 新增 - 初始化表单对象
        this.meetingRoomForm = {
          id: '',
          create_time: null,
          update_time: null,
          creator: this.useName,
          process_status: '',
          sys_update_user: this.useName,
          sys_audit_user: '',
          sys_audit_time: null,
          sys_deleted: 0,
          meetingRoomData: '',
          meetingRoomTime: '',
          meetingRoomTopic: '',
          meetingRoomCancel: '',
          meetingRoomTimeEnd: '',
        };
        // 重置时间选择
        this.startTime = '';
        this.endTime = '';
        this.dialogVisible = true;
        console.log('Booking 对话框已打开');
      }
      else if (doe === 2) {
        // 编辑 - 复制现有数据到表单对象
        if (scope && scope.row) {
          this.meetingRoomForm = _.cloneDeep(scope.row);
          // 设置时间选择器
          this.startTime = scope.row.meetingRoomTime;
          this.endTime = scope.row.meetingRoomTimeEnd;
          this.dialogVisible = true;
          console.log('编辑对话框已打开', scope.row);
        }
      }
    },

    //退出登录
    logOut(){
      localStorage.removeItem('u_token');
      localStorage.removeItem('userName')
      this.$router.push('UserLogin')
    },

    //查询用户信息的函数
    inquiry() {
      //输入用户编号，向后端查询信息
      const useId = localStorage.getItem('userName').replace(/"/g, '');
      this.$request.post('/useQueryPower', {
        queryFiledName: 'goodProductCondition',
        userId: useId,
      }).then(result => {
        if (result.code === 401) {
          this.$router.push('UserLogin')
          alert("您未登录，请登录")
        } else {
          this.useName = result.data.name
          this.usePower = result.data.goodProductCondition
          this.useId = useId
        }
      })
    },

    async queryMeetingRoomAll() {
      try {
        const result = await this.$request.post('/queryMeetingRoom');
        if (result.code === 401) {
          this.$router.push('UserLogin');
          this.$message.error("您未登录，请登录");
          return [];
        } else {
          // 直接返回所有数据
          const allData = Array.isArray(result.data) ? result.data : [];
          console.log('查询到的会议数据:', allData);
          return allData;
        }
      } catch (error) {
        console.error('API请求失败:', error);
        this.$message.error('网络连接失败，请检查服务器状态');
        return [];
      }
    },

    languageSelect(language){
      console.log(language);
      // 语言切换的逻辑
      switch(language) {
        case 'chinese':
          this.main = {
            qualityManagementSystem: '会议室管理系统',
            goodProductConditions: '会议室预定日程',
            resignManagement: '预定',
            dressingRoom: '删除'
          };
          break;
        case 'english':
          this.main = {
            qualityManagementSystem: 'MeetingRoom',
            goodProductConditions: 'MeetingRoom Schedule',
            resignManagement: 'Booking',
            dressingRoom: 'Delete'
          };
          break;
        case 'russian':
          this.main = {
            qualityManagementSystem: 'Переговорная',
            goodProductConditions: 'Расписание переговорной',
            resignManagement: 'Бронирование',
            dressingRoom: 'Удалить'
          };
          break;
      }
      this.languageS = language;
    }
  },
  mounted() {
    console.log('组件挂载，开始加载数据');
    this.inquiry();
    // 初始加载数据到表格数组
    this.refreshMeetingRoomData();
  },

  computed: {
    // 计算属性
    hasMeetingData() {
      return this.meetingRoomList && this.meetingRoomList.length > 0;
    }
  }
}
</script>